import '@css/sellersPage.css'

window.addEventListener("DOMContentLoaded", async () => {


  document.getElementById("claimManageBtn").style.display = "block"
  document.getElementById("yourclaimBtn").style.background = "gray"
  document.getElementById("yourclaimBtn").style.color = "white"

  newLoad()

  document.querySelector("#rightTop").innerHTML = `
  <p id="searchClaimBox">请输入用户名进行搜索<input id="searchClaimcontent"><button id="searchClaimBtn">点击搜索</button></p>
  <div id="addClaimBox"><button id="addClaimBtn">+新增一个理赔申请</button></div>
  `
  //用户信息管理
  // document.querySelector('#userListBtn').addEventListener('click', () => {
  //   location = `userPage.html`
  // })


  //标签卡的切换
  await document.querySelector('#claimsListBtn').addEventListener('click', async () => {
    location = `salerClaimPage.html`
  })
  await document.querySelector('#userListBtn').addEventListener('click', async () => {
    location = `salerUserPage.html`
  })

})


document.querySelector("body").addEventListener("click", async (e) => {
  if (e.target.tagName == "A") {
    e.preventDefault()
  }
  //跳转到首页
  if (e.target.className == "salertitle") {
    window.location.href = "sellersPage.html"
  }

  // 删除单个保单
  if (e.target.className == "claimdelete") {
    delOneClaims(e.target.parentElement.parentElement.firstElementChild.innerHTML)
  }
  // 修改单个保单
  if (e.target.className == "claimmodify") {
    //渲染页面
    await modifyClaim(e.target.parentElement.parentElement.firstElementChild.innerHTML)
    document.querySelector("#uploadVoucher").addEventListener("change", async function () {
      console.log(this.files[0]);
      const { code, message, avatarPath } = await avatarUploadApi(this.files[0])
      if (code) {
        // console.log(avatarPath);
        document.querySelector("#showVoucherImg").setAttribute("src", `http://127.0.0.1:3000/images/${avatarPath}`)

      }

    })
  }
  if (e.target.id == "makeSureClaim") {
    const result = await modifyContent()
    alert("修改成功")
    newLoad()
  }

  //模糊搜索事件绑定
  if (e.target.id == "searchClaimBtn") {
    let content = document.querySelector("#searchClaimcontent").value
    console.log(document.querySelector("#searchClaimcontent"));
    const { rows } = await searchClaim(content)

    let newArr = rows.filter(item => {
      return !item.delete
    })
    reload(newArr)
    console.log(rows);
  }

  //增加功能区

  //增加理赔专用

  if (e.target.id == "addClaimBtn" || e.target.getAttribute('data-id') == "addClaimsBtn") {
    addClaimFirst()
    document.querySelector("#uploadVoucher").addEventListener("change", async function () {
      console.log(this.files[0]);
      const { code, message, avatarPath } = await avatarUploadApi(this.files[0])
      if (code) {
        // console.log(avatarPath);
        document.querySelector("#showVoucherImg").setAttribute("src", `http://127.0.0.1:3000/images/${avatarPath}`)
        // alert(document.querySelector("#showVoucherImg").getAttribute("src"))
      }

    })
  }

  //确认增加按钮
  if (e.target.id == "makeSureAddClaim") {
    const result = await addClaimContent()
    alert(result)
    // alert("增加成功")
    newLoad()
  }

  //取消执行操作按钮
  if (e.target.id == "cancelClaim") {
    newLoad()
  }

})



//审核内容第一步，先渲染页面

//上传文件
//上传图片,这里的参数就是上传的文件
const avatarUploadApi = (itemObj) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("POST", "http://127.0.0.1:3000/upload/profile", true)
    // xhr.setRequestHeader('Authorization', localStorage.getItem('token'))
    //使用表单数据
    let formdata = new FormData();
    //在表单数据中添加一个名为avatar的文件
    formdata.append("avatar", itemObj)
    console.log(itemObj);
    //发送表单数据
    xhr.send(formdata)
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}


//增加一个理赔订单流程,第一步渲染
const addClaimFirst = async () => {

  document.querySelector("#rightList").innerHTML =
    `
    <table id="claimModifyTable">
  <tr><td>客户</td><td><input  id="nameClaimInput" placeholder="请输入客户姓名"></td></tr>
  <tr><td>理赔原因</td><td><input id="reasonClaimInput" placeholder="请输入理赔原因"></td></tr>
  <tr><td>理赔金额</td><td><input id="lossesClaimInput" placeholder="请输入理赔金额"></td></tr>
  <tr><td>保险名称</td><td><input id="insurClaimInput" placeholder="请输入保险名称"></td></tr>
  <tr><td>创建时间</td><td><input id="timeClaimInput" disabled="disabled" value="${new Date()}"></td></tr>
  <tr id="showVoucherBox"><td>上传图片</td><td><img id="showVoucherImg"></img><input id="uploadVoucher" type="file" "></td></tr>
  <tr><td></td><td><button id="makeSureAddClaim">确认申请</button><button id="cancelClaim">取消</button></td></tr>
    `
}
//第二步，获取内容并提交申请
export const addClaimContent = async () => {

  let userCode = document.querySelector("#nameClaimInput").value
  let losses = document.querySelector("#lossesClaimInput").value
  let reason = document.querySelector("#reasonClaimInput").value

  let insurancesCode = document.querySelector("#insurClaimInput").value
  let datenow = document.querySelector("#timeClaimInput").value
  //在后端转译代码

  alert(document.querySelector("#uploadVoucher").value)

  let voucher = document.querySelector("#showVoucherImg").getAttribute("src")

  let arr = { voucher, userCode, losses, reason, insurancesCode, datenow }
  console.log(arr);
  const result = await addClaimReal(arr)
  //传输数据
  console.log(result);
}

document.querySelectorAll("h3").forEach(item => {
  item.addEventListener("click", async () => {
    if (item.style.backgroundColor != "gray") {
      item.style.backgroundColor = "gray"
      item.style.color = "white"
    } else {
      item.style.backgroundColor = "#485069"
      item.style.color = "rgb(175, 175, 175)"

    }
  })
})

//修改页面之第一步渲染，点击传入_id，获取对应信息，然后渲染页面
export const modifyClaim = async (itemID) => {

  let { rows } = await getOneClaims(itemID)
  let item = rows
  console.log(item);

  document.querySelector("#rightList").innerHTML =
    `
    <table id="claimModifyTable">
  <tr><td>编号</td><td id="insurClaimID">${item._id}</td></tr>
  <tr><td>客户</td><td><input disabled="disabled" id="nameClaimInput" value="${item.userCode.userName}"></td></tr>
  <tr><td>理赔原因</td><td><input id="reasonClaimInput" value="${item.reason}"></td></tr>
  <tr><td>理赔金额</td><td><input id="lossesClaimInput" value="${item.losses}"></td></tr>
  <tr><td>保险名称</td><td><input disabled="disabled" id="insurClaimInput" value="${item.insurancesCode.insurancesName}"></td></tr>
  <tr><td>创建时间</td><td><input id="timeClaimInput" disabled="disabled" value="${item.datenow}"></td></tr>
  <tr id="showVoucherBox"><td>上传图片</td><td><img id="showVoucherImg"" src="${item.voucher}"></img><input id="uploadVoucher" type="file" "></td></tr>
  <tr><td></td><td><button id="makeSureClaim">确认修改</button><button id="cancelClaim">取消</button></td></tr>
    `
}

//修改页面第二步
export const modifyContent = async () => {

  let _id = document.querySelector("#insurClaimID").innerHTML
  let userCode = document.querySelector("#nameClaimInput").value
  let losses = document.querySelector("#lossesClaimInput").value
  let reason = document.querySelector("#reasonClaimInput").value

  let insurancesCode = document.querySelector("#insurClaimInput").value
  let datenow = document.querySelector("#timeClaimInput").value
  //在后端转译代码
  let voucher = document.querySelector("#showVoucherImg").getAttribute("src")

  let arr = { _id, voucher, userCode, losses, reason, insurancesCode, datenow }
  console.log(arr);
  const result = await modifyClaimReal(arr)
  //传输数据
  console.log(result);
}

//增加一个理赔订单Api
const addClaimReal = (arr) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("POST", "http://127.0.0.1:3000/claims/addOneClaim", true)
    xhr.setRequestHeader("content-type", "application/json")
    // xhr.setRequestHeader('Authorization', localStorage.getItem('token'))
    xhr.send(JSON.stringify(arr))
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}

//模糊搜索Api
const searchClaim = async (key) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("GET", `http://127.0.0.1:3000/claims/searchManyClaim/${key}`, true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}

//修改一个理赔订单

const modifyClaimReal = async (arr) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("PUT", "http://127.0.0.1:3000/claims/modifyOneClaim", true)
    xhr.setRequestHeader("content-type", "application/json")
    // xhr.setRequestHeader('Authorization', localStorage.getItem('token'))
    xhr.send(JSON.stringify(arr))
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}
// }


//刷新页面的主体
export const reload = (newArr) => {
  document.querySelector("#rightList").innerHTML = `
<table>
<thead>
<td>编号</td><td>客户</td><td>理赔原因</td><td>理赔金额</td><td>保险名称</td><td>创建时间</td><td>订单状态</td><td>操作</td>
</thead>
<tbody>

`+ newArr.map(item =>
    `
<tr>
<td>${item._id}</td>
<td>${item.userCode.userName}</td>
<td>${item.reason}</td>
<td>${item.losses}</td>
<td>${item.insurancesCode.insurancesName}</td>
<td>${item.datenow.substring(0, 10)}</td>
<td>${item.state == 0 ? "待审核" : "审核通过"}</td>
<td><button class="claimdetail">审核</button>
<button class="claimmodify">修改</button>
<button class="claimdelete">删除</button></td>
</tr>
`
  ).join("") + `</tbody><table>`
}

//获取最新数据并刷新页面
export const newLoad = async () => {
  const { rows } = await getAllClaims()
  console.log(rows);
  let newArr = rows.filter(item => {
    return !item.delete
  })
  reload(newArr)
}

//获取所有理赔订单信息
export const getAllClaims = () => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("GET", "http://127.0.0.1:3000/claims/getAllClaim", true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })

}

//删除一个理赔订单信息
export const delOneClaims = (item) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("PUT", `http://127.0.0.1:3000/claims/delOneClaims/${item}`, true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })

}

//获取指定的理赔订单信息
export const getOneClaims = (item) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("GET", `http://127.0.0.1:3000/claims/getOneClaim/${item}`, true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })

}


